import multiprocessing
import sys
import threading

import webview
from PIL import Image
from pystray import Icon, Menu, MenuItem

import proc_tray
from config import app_data

Process = multiprocessing.Process
Queue = multiprocessing.Queue
webview_process = None


def run_webview(queue):
    threading.Thread(target=web_proc_rev, args=(queue,)).start()
    chinese = {
        'global.quitConfirmation': "确认退出"
    }
    app_data.main_window = webview.create_window('Webview', 'https://pywebview.idepy.com/hello',
                                                 confirm_close=True, localization=chinese)
    app_data.main_window.events.closing += on_closing
    webview.start(icon='assets/logo.ico')


def web_proc_rev(queue):
    print("web_proc_rev")
    while True:
        # 从队列接收消息
        msg = queue.get()
        print(f"Main Received: {msg}")
        if msg == 'exit':
            sys.exit(0)


def start_webview_process(queue):
    # 注意，使用了进程后变量的数据不共享
    webview_process = Process(target=run_webview, args=(queue,))
    webview_process.start()
    return webview_process


def on_closing(window):
    print('pywebview 窗口正在关闭')
    window.create_confirmation_dialog('提示', '应用已隐藏到托盘，你可以从托盘再次打开')
    window.hide()
    return False


if __name__ == '__main__':
    # 创建队列
    queue = multiprocessing.Queue()

    # 创建webview子进程
    web_proc = start_webview_process(queue)

    # 创建子进程
    sub_proc = multiprocessing.Process(target=proc_tray.start_tray, args=(queue,))
    # 启动子进程
    sub_proc.start()

    print("terminate1")
    sub_proc.join()
    print("terminate2")
    web_proc.join()
    print("terminate3")
